package com.tedu._06weibo.exception;

import com.tedu._06weibo.result.JsonResult;
import com.tedu._06weibo.result.Status;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

//@ControllerAdvice
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandlerRuntimeException(RuntimeException e){
        return new JsonResult(Status.OPERATION_ERROR,e.getMessage());
    }

    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException e){
        System.out.println("处理IllegalArgumentException");
        return new JsonResult(Status.OPERATION_ERROR,e.getMessage());
    }
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        String message = e.getFieldError().getDefaultMessage();
        return new JsonResult(Status.VALIDATE_FAILED,message);
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException e){
        String message = e.getMessage();

        message = message.substring(message.indexOf(":")+1).trim();
        return new JsonResult(Status.VALIDATE_FAILED,message);
    }
}
